package com.now.printer.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.now.printer.R;
import com.now.printer.adapter.SearchListResultAdapter;
import com.now.printer.db.DocumentsTable;
import com.now.printer.ui.activity.FilePreviewAndPrintActivity;
import com.now.printer.ui.activity.HtmlPrintActivity;
import com.now.printer.ui.activity.WebViewActivity;
import com.now.printer.utils.DbUtils;
import com.now.printer.utils.FileManager;
import com.now.printer.utils.FileUtils;
import com.now.printer.utils.FileUtils2;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;
import org.xutils.DbManager;
import org.xutils.common.util.LogUtil;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 分类文件
 */
public class SimpleCardFragment extends Fragment {

    private static final String BUNDLE_KEY_FILE_TYPE = "BUNDLE_KEY_FILE_TYPE";
    private static final String BUNDLE_KEY_KEY_WORD = "keyWord";
    int fileType = 0;
    private LinearLayout llEmpty;
    private SearchListResultAdapter searchListResultAdapter;
    //    private MiniLoadingDialog mMiniLoadingDialog;
    private RecyclerView typeRecycler;
    private List<DocumentsTable> documentsTableList = null;
    private List<DocumentsTable> searchResultList = new ArrayList<>();
    private String keyWord;

    public static SimpleCardFragment getInstance(int i, String keyWord) {
        SimpleCardFragment sf = new SimpleCardFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(BUNDLE_KEY_FILE_TYPE, i);
        bundle.putString(BUNDLE_KEY_KEY_WORD, keyWord);
        sf.setArguments(bundle);
        return sf;
    }

    private void initData() {
        searchResultList.clear();

        try {
            DbManager db = x.getDb(DbUtils.daoConfig);
            if (fileType == FileUtils.TYPE_ALL) {
                documentsTableList = db.selector(DocumentsTable.class).findAll();
            } else if (fileType == FileUtils.TYPE_DOC) {
                documentsTableList = db.selector(DocumentsTable.class)
                        .where("name", " LIKE ", "%.doc")
                        .or("name", " LIKE ", "%.docx")
                        .findAll();

            } else if (fileType == FileUtils.TYPE_PPT) {
                documentsTableList = db.selector(DocumentsTable.class)
                        .where("name", " LIKE ", "%.ppt")
                        .or("name", " LIKE ", "%.pptx")
                        .findAll();
            } else if (fileType == FileUtils.TYPE_XLS) {
                documentsTableList = db.selector(DocumentsTable.class)
                        .where("name", " LIKE ", "%.xls")
                        .or("name", " LIKE ", "%.xlsx")
                        .findAll();
            } else if (fileType == FileUtils.TYPE_PDF) {
                documentsTableList = db.selector(DocumentsTable.class)
                        .where("name", " LIKE ", "%.pdf")
                        .findAll();
            } else if (fileType == FileUtils.TYPE_TXT) {
                documentsTableList = db.selector(DocumentsTable.class)
                        .where("name", " LIKE ", "%.txt")
                        .findAll();
            } else if (fileType == FileUtils.TYPE_PIC) {
                documentsTableList = FileManager.getInstance(getActivity()).getAllImagesList();
            }
            LogUtil.i("documentsTableList is :" + documentsTableList);
        } catch (DbException e) {
            e.printStackTrace();
            LogUtil.e("SimpleCardFragment onAttach DbException : " + e.getLocalizedMessage());
            return;
        }

        if (documentsTableList != null) {
            if (TextUtils.equals(keyWord, "")) {
                searchResultList.addAll(documentsTableList);
            } else {
                for (int i = 0; i < documentsTableList.size(); i++) {
                    if (documentsTableList.get(i).getName().contains(keyWord)) {
                        searchResultList.addAll(documentsTableList);
                    }
                }
            }
        }

        if (searchListResultAdapter != null) {
            searchListResultAdapter.notifyDataSetChanged();
//            searchListResultAdapter.setData(searchResultList);
        }
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        fileType = getArguments().getInt(BUNDLE_KEY_FILE_TYPE);
        keyWord = getArguments().getString(BUNDLE_KEY_KEY_WORD);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_simple_card, null);
        llEmpty = (LinearLayout) v.findViewById(R.id.ll_empty);
//        EventBus.getDefault().register(this);
        RefreshLayout refreshLayout = (RefreshLayout) v.findViewById(R.id.refreshLayout);

        RecyclerView typeRecycler = (RecyclerView) v.findViewById(R.id.typeRecycler);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(),
                LinearLayoutManager.VERTICAL, false);
        typeRecycler.setLayoutManager(linearLayoutManager);

        searchListResultAdapter = new SearchListResultAdapter(getActivity(), searchResultList, R.layout.item_search_result_list);
        typeRecycler.setAdapter(searchListResultAdapter);

        //列表点击事件
        searchListResultAdapter.setOnItemClickLitener((position, type) -> {
            LogUtil.i("按下的item path是 ： " + searchResultList.get(position).getPath());
            Intent intent = new Intent();
            intent.setClass(getActivity(), FilePreviewAndPrintActivity.class);

//            if (fileType == FileUtils.TYPE_PIC) {
//                intent.setClass(getActivity(), TuPianActivity.class);
//            } else {
//                if (fileType == FileUtils.TYPE_DOC || fileType == FileUtils.TYPE_XLS || fileType == FileUtils.TYPE_PPT){
//                    //不是pdf格式， 因此直接分享到wps或者office的APP里去转换之后， 再通过三方分享回这里
//                    Intent intent1=new Intent(Intent.ACTION_SEND);
//                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//
////                   Uri uri = FileUtils.getFileUri(getActivity(),new File(searchResultList.get(position).getPath()));
////                   FileUtils2.getFileFromUri(getActivity(),Uri.parse(searchResultList.get(position).getPath()))
//                    intent1.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(searchResultList.get(position).getPath())) );
//                    String mimeType = FileUtils.getMIMEType(new File(searchResultList.get(position).getPath()));
//                    intent1.setType(mimeType);
//                    startActivity(Intent.createChooser(intent1,"使用其他应用打开"));
//                    LogUtil.i("getMimeType ： " + mimeType);
//                    return;
//                }else {
//                    intent.setClass(getActivity(), FilePreviewAndPrintActivity.class);
//                }
//            }
            intent.putExtra(FilePreviewAndPrintActivity.INTENT_KEY_FILE_URI, searchResultList.get(position).getPath());
            intent.putExtra(FilePreviewAndPrintActivity.INTENT_KEY_FILE_NAME, searchResultList.get(position).getName());
            intent.putExtra(FilePreviewAndPrintActivity.INTENT_KEY_FILE_IMAGE, searchResultList.get(position).getImageId());
            intent.putExtra(FilePreviewAndPrintActivity.INTENT_KEY_FILE_LAST_TIME, searchResultList.get(position).getLastTime());
            intent.putExtra(FilePreviewAndPrintActivity.INTENT_KEY_FILE_SIZE, searchResultList.get(position).getSize());
            startActivity(intent);


        });
        initData();

//        refreshLayout.autoRefresh();
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NotNull RefreshLayout refreshlayout) {
                LogUtil.i("file type is : " + fileType);

                DbUtils.initSystemFileDb(getActivity(), new Handler() {
                    @Override
                    public void handleMessage(@NonNull Message msg) {
                        super.handleMessage(msg);
                        if (msg.what == 1) {
                            initData();
                            refreshlayout.finishRefresh(/*,false*/);//传入false表示刷新失败
                        }
                    }
                });
            }
        });
        return v;
    }


};

//    @Override
//    public void onDestroyView() {
//        super.onDestroyView();
//        EventBus.getDefault().unregister(this);
//    }
//
//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void onReceiveMsg(MessageWrap message) {
//        Log.e("SimpleCardFragment", "onReceiveMsg: " + message.toString());
////        List<FileBean> searchResultList2 = new ArrayList<>();
////        for (int i = 0; i < getInstance(message.type).searchResultList.size(); i++) {
////            if (getInstance(message.type).searchResultList.get(i).getName().contains(message.message)) {
////                searchResultList2.add(searchResultList.get(i));
////            }
////        }
////        getInstance(message.type).searchResultList.clear();
////        getInstance(message.type).searchResultList.addAll(searchResultList2);
////   